package zhongbo.javaweb.instagram.service;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * 说明：
 *
 * @author zhongboWork
 * @version 1.0
 * @since 2021-12-21 10:49
 */
@Service
@Slf4j
public class FileService<ENTITY> {

    public File getUserDirFile(Class<ENTITY> clazz) {
        String simpleName = clazz.getSimpleName();
        String fileName = simpleName + "Data.json";
        String property = System.getProperty("user.dir");
        String pathname = property + File.separator + fileName;
        return new File(pathname);
    }

    public synchronized List<ENTITY> readJsonList(Class<ENTITY> clazz) throws IOException {

        File file = getUserDirFile(clazz);
        if (file.exists()) {
            String jsonStr = readStr(file);
            return JSON.parseArray(jsonStr, clazz);
        }
        return new ArrayList<>();
    }

    public synchronized void writeJsonList(List<ENTITY> tasks, Class<ENTITY> clazz) throws IOException {
        if (tasks != null) {
            File file = getUserDirFile(clazz);
            String jsonString = JSON.toJSONString(tasks);
            writeStr(file, jsonString);
        }
    }

    public synchronized ENTITY readJson(Class<ENTITY> clazz) throws IOException {

        File file = getUserDirFile(clazz);
        if (file.exists()) {
            String jsonStr = readStr(file);
            return JSON.parseObject(jsonStr, clazz);
        }
        try {
            return clazz.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            log.error("clazz has no args constructor, class={}", clazz, e);
        }
        return null;
    }

    public synchronized void writeJson(ENTITY tasks, Class<ENTITY> clazz) throws IOException {
        if (tasks != null) {
            File file = getUserDirFile(clazz);
            String jsonString = JSON.toJSONString(tasks);
            writeStr(file, jsonString);
        }
    }

    private void writeStr(File file, String jsonString) throws IOException {
        FileOutputStream fos = new FileOutputStream(file);
        byte[] bytes = jsonString.getBytes(StandardCharsets.UTF_8);
        fos.write(bytes);
        fos.flush();
        fos.close();
    }

    private String readStr(File file) throws IOException {
        FileInputStream fis = new FileInputStream(file);
        int available = fis.available();
        byte[] bytes = new byte[available];
        int read = fis.read(bytes);
        log.debug("read {} size {}", file, read);
        fis.close();
        return new String(bytes, StandardCharsets.UTF_8);
    }
}
